<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">登录聊天室</h2>
      <el-form :model="form" class="login-form">
        <el-form-item>
          <el-input
            v-model="form.username"
            placeholder="ID"
            prefix-icon="el-icon-user"
            class="input-field"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="form.password"
            type="password"
            placeholder="密码"
            prefix-icon="el-icon-lock"
            class="input-field"
          />
        </el-form-item>
        <el-button
          type="primary"
          class="login-btn"
          @click="handleLogin"
        >
          登录
        </el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    handleLogin() {
      this.$axios.post('/user/login', {
        username: this.form.username,
        password: this.form.password
      }).then(response => {
        if (response.status === 200) {
          localStorage.setItem('user', JSON.stringify({
            username: response.data.data.username,
            token: response.data.data.token,
            role: response.data.data.role
          }))
          this.$axios.post('/message/getChatList', {currentUsername:response.data.data.username}).then(response => {
            localStorage.setItem('chatList', JSON.stringify(response.data.data));
          })
          this.$router.push('/index')
        }
      })
        .catch(error => {
          if (error.response && error.response.status === 401) {
            this.$message.error('用户名或密码错误');
          } else {
            this.$message.error('登录失败，请检查网络连接');
          }
        });
    }
  }
}
</script>

<style scoped>
@import url("../assets/css/views/login.css");
</style>